package org.example.springboot3.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.springboot3.entity.Account;
import org.example.springboot3.entity.Admin;
import org.example.springboot3.exception.CustomException;
import org.example.springboot3.mapper.AdminMapper;
//import org.example.springboot3.utils.TokenUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;

    public List<Admin> selectALL(Admin admin) {
        return adminMapper.selectAll(admin);
    }

    public Admin selectById(Integer id) {
        return adminMapper.selectById(id);
    }
    public Admin selectByName(String username) {
        return adminMapper.selectByUsername(username);
    }

    public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }

    public void add(Admin admin) {
        String username = admin.getUsername();  // 账号
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if (dbAdmin != null) {  // 注册的账号已存在  无法注册
            throw new CustomException("500", "账号已存在，请更换别的账号");
        }
        if (StrUtil.isBlank(admin.getPassword())) {  // 密码没填
            admin.setPassword("123");  // 默认密码 123
        }
        if (StrUtil.isBlank(admin.getUsername())) {
            admin.setUsername(username);
        }
        // 一定要设置角色
        admin.setRole("EMP");  // 员工的角色
        adminMapper.insert(admin);
    }

    public void updata(Admin admin) {
        adminMapper.updataById(admin);
    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            this.deleteById(id);
        }
    }

    public Admin login(Account account) {
        String username = account.getUsername();  // 账号
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if (dbAdmin == null) {  // 没查询到任何用户   说明没有这个账号
            throw new CustomException("500", "账号不存在");
        }
        // 数据库存在这个账号
        String password = account.getPassword();
        if (!dbAdmin.getPassword().equals(password)) {  // 用户输入的密码跟数据库账号的密码不匹配
            throw new CustomException("500", "账号或密码错误");
        }
        //生成JWT
//        String token = TokenUtils.createToken(dbAdmin.getUsername(), dbAdmin.getPassword(), dbAdmin.getRole());
//        dbAdmin.setToken(token);
        return dbAdmin;
    }

    public void register(Admin admin) {
        this.add(admin);
    }
}